#!/usr/bin/perl -w

#######################################################################################
# Program Configuration options
#######################################################################################
use FindBin qw($Bin);
use lib "$Bin";
use config;

#######################################################################################
# Please do not modify below this line unless you truly understand what you are doing.
# I won't provide any assistance if you've modified below this line.
#######################################################################################

#######################################################################################
# Perl Modules
#######################################################################################
use FileHandle;

use DBI;

#######################################################################################
# Program Start
#######################################################################################
my $currentdate = `date "+%Y-%m-%d %H:%M:%S"`;
chomp($currentdate);

my $pngopts = &read_config_option("png_opts");

my %daterangehash = (
    "day"   => `date "+%Y-%m-%d %H:%M:%S" --date="-1 day"`,
    "week"  => `date "+%Y-%m-%d %H:%M:%S" --date="-1 week"`,
    "month" => `date "+%Y-%m-%d %H:%M:%S" --date="-1 month"`,
    "year"  => `date "+%Y-%m-%d %H:%M:%S" --date="-1 year"`
);

# Prepare all DBI calls
my $dbh           = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");
my $graphline_sth = $dbh->prepare("SELECT * FROM graphlines WHERE graphname=? ORDER BY lineposition ASC");
my $test_sth      = $dbh->prepare("SELECT * FROM tests ORDER BY displayorder ASC");

$test_sth->execute();
while (my $testref = $test_sth->fetchrow_hashref()) {
    my %testhash   = %{$testref};
    my $name       = $testhash{name};
    my $title      = $testhash{title};
    my $column     = ($testhash{displayorder} + 2);    # The graph data file contains two extra columns at the beginning!
    my $minrange   = $testhash{graphmin};
    my $maxrange   = $testhash{graphmax};
    my $linecolour = $testhash{graphlinecolour};
    my $avgcolour  = $testhash{graphavgcolour};

    foreach $xrange (keys %daterangehash) {
        chomp($daterangehash{$xrange});

        open(GP, "|$gnuplot") or die "no gnuplot";
        GP->autoflush(1);
        print GP "set terminal png $pngopts\n";
        print GP "set output \"$graphdir/statistics-$name-$xrange.png\"\n";
        print GP "set xdata time\n";
        print GP "set timefmt \"%Y-%m-%d %H:%M:%S\"\n";

        # Set x axis label format
        if ($xrange eq "day") {
            print GP "set format x \"%H\"\n";
        } elsif ($xrange eq "week") {
            print GP "set format x \"%a\"\n";
        } elsif ($xrange eq "month") {
            print GP "set format x \"%b %d\"\n";
        } else {
            print GP "set format x \"%b\"\n";
        }

        print GP "set xrange [\"$daterangehash{$xrange}\":\"$currentdate\"]\n";
        if ($debug == 1) {
            print "set xrange [\"$daterangehash{$xrange}\":\"$currentdate\"]\n\n";
        }

        if ((defined($minrange)) and (defined($maxrange))) {
            print GP "set yrange [\"$minrange\":\"$maxrange\"]\n";
        } elsif (defined($minrange)) {
            print GP "set yrange [\"$minrange\":]\n";
        } elsif (defined($maxrange)) {
            print GP "set yrange [:\"$maxrange\"]\n";
        }
        print GP "set pointsize 0.5\n";
        print GP "set datafile missing 'NaN'\n";
        print GP "plot \"$graphdatafile\" using 1:$column  title \"$title\" with lines linecolor rgb \"$linecolour\" lw 2,";
        if ($debug == 1) {
            print "plot \"$graphdatafile\" using 1:$column  title \"$title\" with lines linecolor rgb \"$linecolour\" lw 2,\n\n";
        }
        print GP " \"$graphdatafile\" using 1:$column  title \"$title avg\" smooth sbezier with lines linecolor rgb \"$avgcolour\" lw 1";

        # Draw additional graph lines
        $graphline_sth->execute($name);
        while (my $lineref = $graphline_sth->fetchrow_hashref()) {
            my %linehash = %{$lineref};

            print GP ", $linehash{lineposition} notitle with points pointsize 0.1 linecolor rgb \"$linehash{linecolour}\" lw 1";
        }
        print GP "\n";
        close GP;
    }
}

# Draw a complete with everything graph... not very useful, but colourful! :)
open(GP, "|$gnuplot -persist") or die "no gnuplot";
GP->autoflush(1);
print GP "set terminal png size 400,200 tiny\n";
print GP "set output \"$graphdir/statistics.png\"\n";
print GP "set xdata time\n";

#print GP "set format x \"%H\"\n";
print GP "set format x \"%b %d\"\n";
print GP "set timefmt \"%Y-%m-%d %H:%M:%S\"\n";
print GP "set xrange [\"$daterangehash{month}\":\"$currentdate\"]\n";

my @plotlines;
$test_sth->execute();
while (my $testref = $test_sth->fetchrow_hashref()) {
    my %testhash   = %{$testref};
    my $name       = $testhash{name};
    my $title      = $testhash{title};
    my $column     = ($testhash{displayorder} + 2);    # The graph data file contains two extra columns at the beginning!
    my $linecolour = $testhash{graphlinecolour};

    push(@plotlines, "\"$graphdatafile\" using 1:$column title \"$title\" with lines linecolor rgb \"$linecolour\"");
}
print GP "plot ", join(", ", @plotlines), "\n";
close GP;

$dbh->disconnect();
exit 0;

